package services.common;

import java.io.File;
import java.security.InvalidParameterException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.shove.Convert;

import models.common.bean.CurrUser;
import models.common.entity.t_commercial_paper_info;
import models.common.entity.t_commercial_paper_lines;
import models.common.entity.t_commercial_paper_info.TicketStatus;
import models.common.entity.t_commercial_paper_lines.PaperType;
import models.common.entity.t_company_info;
import models.common.entity.t_creditor_right_debt;
import models.common.entity.t_deal_platform;
import models.common.entity.t_deal_user;
import models.common.entity.t_deal_user.OperationType;
import models.common.entity.t_digital_commercial_paper;
import models.common.entity.t_digital_commercial_paper.DigitalStatus;
import models.common.entity.t_endorse;
import models.common.entity.t_event_user;
import models.common.entity.t_flow_switch;
import models.common.entity.t_user;
import models.common.entity.t_user_credit;
import models.common.entity.t_user_credit.AuditResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import models.common.entity.t_user_credit_detail;
import models.common.entity.t_user_fund;
import play.db.jpa.JPAPlugin;
import play.mvc.Http.Request;
import services.base.BaseService;
import common.constants.ConfConst;
import common.constants.Constants;
import common.constants.SettingKey;
import common.enums.NoticeScene;
import common.enums.ServiceType;
import common.utils.DateUtil;
import common.utils.Factory;
import common.utils.FeeCalculateUtil;
import common.utils.ImgUtil;
import common.utils.LoggerUtil;
import common.utils.OrderNoUtil;
import common.utils.PageBean;
import common.utils.ResultInfo;
import common.utils.Security;
import common.utils.excel.ExcelUtils;
import common.utils.jsonAxml.JsonDateValueProcessor;
import common.utils.jsonAxml.JsonDoubleValueProcessor;
import common.utils.number.Arith;
import daos.common.DigitalCommercialPaperDao;

/**
 * 数字凭证表service
 * 
 * @author xiaojun
 * @version 2017-4-14 下午4:36:26
 */
public class DigitalCommercialPaperService extends
		BaseService<t_digital_commercial_paper> {

	private DigitalCommercialPaperDao digitalCommercialPaperDao;
	protected static UserFundService userFundService = Factory
			.getService(UserFundService.class);
	protected static NoticeService noticeservice = Factory
			.getService(NoticeService.class);
	protected static DealUserService dealuserservice = Factory
			.getService(DealUserService.class);
	protected static CommerciaPaperiInfoService commerciaPaperiInfoService = Factory
			.getService(CommerciaPaperiInfoService.class);

	protected DigitalCommercialPaperService() {
		digitalCommercialPaperDao = Factory
				.getDao(DigitalCommercialPaperDao.class);
		super.basedao = digitalCommercialPaperDao;
	}

	protected static CreditorRightDebtService creditorRightDebtService = Factory
			.getService(CreditorRightDebtService.class);

	protected static DealUserService dealUserService = Factory
			.getService(DealUserService.class);

	protected static EndorseService endorseService = Factory
			.getService(EndorseService.class);

	protected static AmountDetailService amountDetailService = Factory
			.getService(AmountDetailService.class);
	protected static CompanyInfoService companyInfoService = Factory
			.getService(CompanyInfoService.class);
	protected static FlowSwitchService flowSwitchService = Factory
			.getService(FlowSwitchService.class);

	protected static UserCreditService userCreditService = Factory
			.getService(UserCreditService.class);
	/** 注入系统设置service */
	protected static SettingService settingService = Factory
			.getService(SettingService.class);

	protected static DealPlatformService dealPlatformService = Factory
			.getService(DealPlatformService.class);

	protected static NoticeService noticeService = Factory
			.getService(NoticeService.class);

	protected static UserCreditDetailService userCreditDetailService = Factory
			.getService(UserCreditDetailService.class);

	protected static DigitalCommercialPaperService digitalCommercialPaperService = Factory
			.getService(DigitalCommercialPaperService.class);
	
	protected static UserService userService = Factory
			.getService(UserService.class);
	
	protected static CommerciaPaperLinesService commerciaPaperLinesService = Factory
			.getService(CommerciaPaperLinesService.class);
	/**
	 * 更新数字凭证表数据
	 * 
	 * @param t
	 *            数字凭证实体
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */
	public t_digital_commercial_paper saveDigitalPapre(
			t_digital_commercial_paper t) {

		return digitalCommercialPaperDao.saveT(t);
	}

	/**
	 * 
	 * 
	 * @param code
	 * @return
	 * @author xiaojun
	 * @version 2018-1-31
	 */
	public String getGrantingCcode(String code) {
		t_digital_commercial_paper dcp = null;
		for (int i = 1; i > 0; i++) {
			code = code + "-" + i;
			dcp = findByColumn(" certificate_code = ?", code);
			if (dcp == null) {
				return code;
			}
		}
		return code + "*1";
	}

	/**
	 * 更新数字凭证表状态
	 * 
	 * @param t
	 *            数字凭证实体
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */

	public boolean updateStatus(int status, int olStatus, long id) {
		return digitalCommercialPaperDao.updateStatus(status, olStatus, id);
	}

	/**
	 * 更新数字凭证表还款状态
	 * 
	 * @param t
	 *            数字凭证实体
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */
	public boolean updateStatus(int status, int olStatus, long id,
			int repayment_status, int is_endorse) {
		return digitalCommercialPaperDao.updateStatus(status, olStatus, id,
				repayment_status, is_endorse);
	}

	/**
	 * 背书
	 * 
	 * @param id
	 *            数字凭证id
	 * @param creditorId
	 *            债权id
	 * @return
	 * @author xiaojun
	 * @version 2017-8-3
	 */
	public ResultInfo endorseApply(long id, long creditorId) {
		ResultInfo result = new ResultInfo();
		

		// 背书控制开关
		t_flow_switch flowSwitch = flowSwitchService.findByID(1);
		// 背书控制开关
		if (flowSwitch.flow_switch == 1) {
			result.code = -1;
			result.msg = "背书功能已关闭！";
			return result;
		}
		
		t_digital_commercial_paper dcp = findByID(id);
		if (dcp == null) {
			result.code = -1;
			result.msg = "数据异常！";
			return result;
		}
		if (DigitalStatus.CONFIRM.code != dcp.digital_com_status) {
			result.code = -1;
			result.msg = "状态非法！";
			return result;
		}
		// 修改数字凭证状态
		dcp.digital_com_status = t_digital_commercial_paper.DigitalStatus.ENDORSE.code;
		dcp.is_endorse = 1;
		boolean save = updateStatus(DigitalStatus.ENDORSE.code,
				DigitalStatus.CONFIRM.code, id, dcp.repayment_status,
				dcp.is_endorse);
		if (!save) {
			LoggerUtil.error(true, "更新数字凭证状态异常");
			result.code = -1;
			result.msg = "更新数字凭证状态异常";
			return result;
		}

		t_commercial_paper_info cpi = commerciaPaperiInfoService
				.findByID(dcp.commer_paper_id);
		
		if (creditorId <= 0) {
			result.code = -1;
			result.msg = "请选择一个债务信息";
			return result;
		}
		t_creditor_right_debt crd = creditorRightDebtService
				.findByID(creditorId);
		
		//查看背书人授信信息
		t_user_credit userCreditOral = userCreditService
				.findByID(dcp.company_credit_id);
		
		// 查看被背书人授信信息
		t_user_credit user_credit = userCreditService
				.findByID(dcp.receive_credit_id);
		
		t_user_credit userCredit = userCreditService.findByUserTransfer(
				crd.company_id, cpi.receive_credit_id, user_credit.credit_granting_code);
		if (userCredit == null) {
			userCredit = new t_user_credit();
			userCredit.time = new Date();
			userCredit.setStatus(AuditResult.TRANSFER);
			userCredit.user_id = crd.company_id;
			userCredit.user_name = crd.creditor_name;
			userCredit.credit_granting_code = userCreditService
					.getGrantingCcode(user_credit.credit_granting_code);
			userCredit.start_time = user_credit.start_time;
			userCredit.end_time = user_credit.end_time;
			userCredit.financing_confine_limit = user_credit.financing_confine_limit;
			userCredit.bond_percent = user_credit.bond_percent;
			userCredit.custodian_fee = user_credit.custodian_fee;
			userCredit.flow_limit = user_credit.flow_limit;
			userCredit.parent_id = cpi.receive_credit_id;
			userCredit.lender_id = user_credit.lender_id;
			userCredit.lender_name = user_credit.lender_name;
		}
		userCredit.transferee_limit += dcp.digital_com_paper_money;
		userCredit.transferee_used_limit += dcp.digital_com_paper_money;
		userCredit.usable_limit += dcp.digital_com_paper_money;
		boolean saveCredit = userCreditService.save(userCredit);
		if (!saveCredit) {
			LoggerUtil.error(false, "更新收票人授信额度异常");
			result.code = -1;
			result.msg = "更新收票人授信额度异常";
			return result;
		}

		// 背书表
		t_endorse endorse = new t_endorse();
		endorse.lender_id = dcp.lender_id;
		endorse.lender_name = dcp.lender_name;
		endorse.finacing_ratio = dcp.finacing_ratio;
		endorse.credit_limit_id = dcp.receive_credit_id;
		endorse.commer_paper_id = dcp.commer_paper_id;

		endorse.endorse_company_id = dcp.receive_id;
		endorse.debt_creditor_id = crd.id;
		endorse.endorse_company_name = dcp.receive_person;
		endorse.contract_name_code = crd.contract_name_code;
		endorse.bill_money = dcp.digital_com_paper_money;
		endorse.finacing_limit = Arith.div(dcp.digital_com_paper_money
				* dcp.finacing_ratio, 100, 2);
		endorse.endoresd_company_name = crd.creditor_name;
		endorse.certificate_code = "2-" + dcp.certificate_code.substring(2);
		if (crd.company_id <= 0) {
			result.code = -1;
			result.msg = "被背书人未在平台注册，无法背书！";
			return result;
		}
		endorse.endoresd_company_id = crd.company_id;
		endorse.endorse_time = new Date();
		endorse.payment_time = dcp.payment_time;
		dcp.certificate_code = endorse.certificate_code;
		endorse.paper_pic_on = ImgUtil.screenshot(dcp, 1, cpi, null);
		endorse.paper_pic_under = dcp.digital_com_pic_under;
		endorse.original_id = dcp.commer_paper_id;
		endorse.digital_id = dcp.id;
		endorse.company_credit_id = dcp.receive_credit_id;
		endorse.receive_credit_id = userCredit.id;
		endorse.finacing_residue_limit = dcp.digital_com_paper_money;
		save = endorseService.saveEndorse(endorse);
		if (!save) {
			LoggerUtil.error(true, "更新背书表数据异常");
			result.code = -1;
			result.msg = "更新背书表数据异常！";
			return result;
		}


		// 更新债权债务表的剩余额度数据
		crd.rest_debt_money -= dcp.digital_com_paper_money;
		if (crd.rest_debt_money < 0) {
			LoggerUtil.error(true, "债权剩余金额不能小于背书金额");
			result.code = -1;
			result.msg = "债权剩余金额不能小于背书金额！";
			return result;
		}
		if (crd.rest_debt_money == 0) {
			//crd.status = t_creditor_right_debt.CreditorRightDebtStatus.LOSE_EFFICACY.code;
		}
		boolean saveDebt = creditorRightDebtService.addCreditorRightDebt(crd);
		if (!saveDebt) {
			LoggerUtil.error(true, "债权剩余金额更新异常");
			result.code = -1;
			result.msg = "债权剩余金额更新异常！";
			return result;
		}
		// 计算背书额度
		result = endorseService.endorseCredit(endorse, dcp.receive_credit_id, cpi.receive_credit_id);
		if (result.code < 1) {
			LoggerUtil.error(true, "债权剩余金额更新异常");
			return result;
		}
		result.code = 1;
		result.msg = "背书操作成功！";
		return result;
	}
	

	/**
	 * 前台- 账户中心- 交易管理-数字凭证-开出的数字凭证-确认收票
	 * 
	 * @param id
	 *            数字凭证的id
	 * @return
	 * @author xiaojun
	 * @version 2017-8-2
	 */
	public ResultInfo confirmTicket(long id, long userid) {
		ResultInfo result = new ResultInfo();
		t_digital_commercial_paper digital_commercial_paper = findByID(id);
		if (null == digital_commercial_paper
				|| digital_commercial_paper.digital_com_status != DigitalStatus.TBC.code) {
			result.code = -1;
			result.msg = "状态非法！";
			return result;
		}
		if (userid != digital_commercial_paper.receive_id) {
			result.code = -1;
			result.msg = "操作非法！";
			return result;
		}
		t_commercial_paper_info cpi = commerciaPaperiInfoService
				.findByID(digital_commercial_paper.commer_paper_id);
		// 更新数字凭证状态
		digital_commercial_paper.invoice_time = new Date();
		digital_commercial_paper.digital_com_status = t_digital_commercial_paper.DigitalStatus.CONFIRM.code;
		digital_commercial_paper.digital_com_pic_on = ImgUtil.screenshot(
				digital_commercial_paper, 1, cpi, null);
		digital_commercial_paper.digital_com_pic_under = ImgUtil.screenshot(
				digital_commercial_paper, 3, cpi, null);
		digital_commercial_paper.finacing_residue_limit = digital_commercial_paper.digital_com_paper_money;
		digital_commercial_paper = saveDigitalPapre(digital_commercial_paper);
		if (digital_commercial_paper == null) {
			LoggerUtil.error(true, "更新数字凭证状态异常");
			result.code = -1;
			result.msg = "更新数字凭证状态异常";
			return result;
		}
		// 更新商票持票人、商票的图片
		cpi.receive_id = digital_commercial_paper.receive_id;
		cpi.paper_pic_on = digital_commercial_paper.digital_com_pic_on;
		cpi.paper_pic_under = digital_commercial_paper.digital_com_pic_under;
		cpi.is_listing = 1;// 1 标识可挂牌
		cpi.circulation_id = digital_commercial_paper.id;
		cpi = commerciaPaperiInfoService.addTicket(cpi);
		if (cpi == null) {
			LoggerUtil.error(true, "更新商票数据异常");
			result.code = -1;
			result.msg = "更新商票数据异常";
			return result;
		}
		t_user_credit user_credit = userCreditService
				.findByID(digital_commercial_paper.credit_limit_id);
		if (user_credit == null) {
			LoggerUtil.error(true, "获取不到该授信额度信息");
			result.code = -1;
			result.msg = "获取不到该授信额度信息";
			return result;
		}
		// 获取上一级商票的信息
		t_commercial_paper_info orgcpi = commerciaPaperiInfoService
				.findByID(digital_commercial_paper.original_id);

		// 商票类型
		int isDigital = orgcpi.is_digital;

		// 商票到期日期
		Date paperExpireTime = digital_commercial_paper.payment_time;

		// 登记时间
		Date time = digital_commercial_paper.pledge_current_time;
		
		if(time.compareTo(paperExpireTime)!=-1){
			result.code = -1;
			result.msg = "开票的日期不能大于商票的截止日期";
			return result;
		}

		// 两个日期相隔的天数
		int dateCount = DateUtil.getDaysDiffCeil(time, paperExpireTime);
/*
		double custodian_fee = Arith.div(Arith.mul(Arith.mul(
				digital_commercial_paper.digital_com_paper_money,
				user_credit.custodian_fee), dateCount), Arith.mul(30, 100), 2);
*/	
		//票信额度管理费
		double custodian_fee = FeeCalculateUtil.getTransfer(digital_commercial_paper.digital_com_paper_money, time, paperExpireTime, user_credit.custodian_fee);
		
		// 票信流转服务费费率
		double fee = Double.valueOf(settingService
				.findSettingValueByKey(SettingKey.CUSTODIAN_FEE));
		
		//票信流转服务费
		double leader_custodian_fee = FeeCalculateUtil.getTransfer(digital_commercial_paper.digital_com_paper_money,time , paperExpireTime, fee);

		
		// 计算费用
		if(user_credit.parent_id != 0 && custodian_fee > 0){
			result = userTransaction(digital_commercial_paper.company_id,
					digital_commercial_paper.lender_id, custodian_fee,
					digital_commercial_paper.certificate_code, dateCount);
		}
		// 计算票信流转服务费用
		if(user_credit.parent_id != 0 && leader_custodian_fee > 0){
			result = lenderTransaction(user_credit.lender_id, leader_custodian_fee, digital_commercial_paper.certificate_code, dateCount);
			if (result.code < 0) {
				LoggerUtil.error(true, "收取票信流转服务费异常");
				return result;
			}
		}
		if (result.code < 0) {
			LoggerUtil.error(true, "更新数字凭证状态异常");
			return result;
		}
		int upStatus = commerciaPaperiInfoService.upPaperStatus(
				TicketStatus.CONFIRM.code, TicketStatus.TBC.code, cpi.id);
		if (upStatus != 1) {
			LoggerUtil.error(true, "更新数字凭证状态异常");
			result.code = -1;
			result.msg = "更新商票状态异常";
			return result;
		}
		
		t_company_info company_info_com = null;
		t_company_info company_info_recei = null;
		company_info_com = companyInfoService
					.findByUserId(digital_commercial_paper.company_id);
		company_info_recei = companyInfoService
					.findByUserId(digital_commercial_paper.receive_id);
		if (company_info_com == null) {
			result.code = -1;
			result.msg = "开票企业信息异常";
			return result;
		}
		
		if (company_info_recei == null) {
			result.code = -1;
			result.msg = "收票企业信息异常";
			return result;
		}
		
		// 发送通知
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("drawee", company_info_com.full_name);
		param.put("user_name", company_info_recei.full_name);
		param.put("certificate_code", digital_commercial_paper.certificate_code);
		noticeService.sendSysNotice(company_info_com.user_id,
				NoticeScene.OPEN_TIOCKET_AFFIRM_OK, param);
				
		result.code = 1;
		result.msg = "操作成功！状态更新为：" + digital_commercial_paper.getStatus().value;
		return result;
	}

	/**
	 * 票信额度管理费收取费用
	 * 
	 * @param company_id
	 * @param lender_id
	 * @param amount
	 * @param dateCount
	 * @return
	 * @author xiaojun
	 * @version 2018-1-15
	 */
	public ResultInfo userTransaction(long company_id, long lender_id,
			double amount, String certificate_code, int dateCount) {
		ResultInfo result = new ResultInfo();
		if (amount <= 0) {
			result.code = 1;
			return result;
		}
		// 扣除额度管理费(扣除开票用户冻结金额)
		boolean saveFreeze = userFundService.userFundMinusFreezeAmt(company_id,
				amount);
		if (!saveFreeze) {
			result.code = -1;
			result.msg = "扣除额度管理费失败";
			return result;
		}
		t_user_fund userFund = userFundService
				.queryUserFundByUserId(company_id);
		String serviceOrderNo = OrderNoUtil.getNormalOrderNo(
				ServiceType.USER_TRANSFER, "");
		/** 添加用户交易记录 */
		Map<String, String> summaryPrams = new HashMap<String, String>();
		summaryPrams.put("certificate_code", certificate_code);
		summaryPrams.put("amount", amount + "");
		boolean addDeal = dealUserService.addDealUserInfo(
				serviceOrderNo, // 订单号
				company_id, amount, userFund.balance, userFund.freeze,
				t_deal_user.OperationType.CUSTODIAN_FEE_PAY, summaryPrams);

		if (!addDeal) {
			result.code = -1;
			result.msg = "添加交易记录失败！";
			return result;
		}
		// 收取额度管理费(增加放款人用户金额)
		saveFreeze = userFundService.userFundAdd(lender_id, amount);
		if (!saveFreeze) {
			result.code = -1;
			result.msg = "收取额度管理费";
			return result;
		}
		t_user_fund lenderUserFund = userFundService
				.queryUserFundByUserId(lender_id);
		serviceOrderNo = OrderNoUtil.getNormalOrderNo(
				ServiceType.USER_TRANSFER, "");
		/** 添加用户交易记录 */
		addDeal = dealUserService.addDealUserInfo(
				serviceOrderNo, // 订单号
				lender_id, amount, lenderUserFund.balance ,
				lenderUserFund.freeze,
				t_deal_user.OperationType.CUSTODIAN_FEE_INCOME, summaryPrams);

		if (!addDeal) {
			result.code = -1;
			result.msg = "添加交易记录失败！";
			return result;
		}
		result.code = 1;
		return result;
	}
	/**
	 * 票信流转受让服务费收取(背书、转开时平台收取)
	 * 
	 * @param company_id
	 * @param lender_id
	 * @param amount
	 * @param dateCount
	 * @return
	 * @author liangqiongfeng
	 * @version 2018-04-24
	 */
	public ResultInfo lenderTransaction(long lender_id,
			double amount, String certificate_code, int dateCount) {
		ResultInfo result = new ResultInfo();
		if (amount <= 0) {
			result.code = 1;
			return result;
		}
		// 扣除票信流转服务费(扣除放款人冻结金额)
		boolean saveFreeze = userFundService.userFundMinusFreezeAmt(lender_id,
				amount);
		if (!saveFreeze) {
			result.code = -1;
			result.msg = "扣除票信流转受让服务费失败";
			return result;
		}
		t_user_fund userFund = userFundService
				.queryUserFundByUserId(lender_id);
		String serviceOrderNo = OrderNoUtil.getNormalOrderNo(
				ServiceType.USER_TRANSFER, "");
		/** 添加用户交易记录 */
		Map<String, String> summaryPrams = new HashMap<String, String>();
		summaryPrams.put("certificate_code", certificate_code);
		summaryPrams.put("amount", amount + "");
		boolean addDeal = dealUserService.addDealUserInfo(
				serviceOrderNo, // 订单号
				lender_id, amount, userFund.balance, userFund.freeze,
				t_deal_user.OperationType.CUSTODIAN_PAY_PLAT_CREDIT, summaryPrams);
		
		if (!addDeal) {
			result.code = -1;
			result.msg = "添加票信流转受让服务费交易记录失败！";
			return result;
		}
		// 增加平台收支记录
		Map<String, Object> dealRemarkParam = new HashMap<String, Object>();
		dealRemarkParam.put("certificate_code", certificate_code);
		dealRemarkParam.put("amount", amount + "");
		addDeal = dealPlatformService.addPlatformDeal(lender_id,
				amount,
				t_deal_platform.DealRemark.CUSTODIAN_FEE_INCOME,
				dealRemarkParam, 0, 0,
				settingService.findSettingValueByKey(SettingKey.COMPANY_NAME));
		if (!addDeal) {
			result.code = -1;
			result.msg = "添加平台收取票信流转受让服务费记录失败";
			
			return result;
		}
		result.code = 1;
		return result;
	}

	/**
	 * 更新数字凭证表数据
	 * 
	 * @param t
	 *            数字凭证实体
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */
	public boolean saveDigitalPapreB(t_digital_commercial_paper t) {
		return digitalCommercialPaperDao.save(t);
	}

	/**
	 * 托收-准备
	 * 
	 * @param id
	 *            数字凭证id
	 * @param user_id
	 *            用户id
	 * @return
	 * @author xiaojun
	 * @version 2017-8-3
	 */
	public ResultInfo collection(long id, long user_id) {
		ResultInfo result = new ResultInfo();
		t_digital_commercial_paper dcp = findByID(id);

		if (dcp == null) {
			result.code = -1;
			result.msg = "查询数字凭证信息失败！";
			return result;
		}
		if (user_id != dcp.receive_id) {
			result.code = -1;
			result.msg = "警告！不是收票人不能操作！";
			return result;
		}
		if (dcp.digital_com_status != DigitalStatus.EXPIRE.code
				&& dcp.digital_com_status != DigitalStatus.OVERDUE.code) {
			result.code = -1;
			result.msg = "状态非法！";
			return result;
		}

		/*t_commercial_paper_info olcpi = commerciaPaperiInfoService
				.findByID(dcp.original_id);*/
		t_commercial_paper_info cpi = commerciaPaperiInfoService
				.findByID(dcp.commer_paper_id);
		if (null == cpi) {
			result.code = -1;
			result.msg = "商票信息异常！";
			return result;
		}
		cpi.collection_status = 1;
		cpi = commerciaPaperiInfoService.addTicket(cpi);
		
		if (cpi == null) {
			result.code = -1;
			result.msg = "商票托收状态更新失败！";
			return result;
		}
		
		dcp.collection_status = 1;
		
		boolean flag = digitalCommercialPaperDao.save(dcp);
		
		if(!flag){
			result.code = -1;
			result.msg = "更新凭证托收状态更新失败！";
			return result;
		}
		
		
		/*olcpi.collection_status = 1;
		olcpi = commerciaPaperiInfoService.addTicket(olcpi);
		if (olcpi == null) {
			result.code = -1;
			result.msg = "商票托收状态更新失败！";
			return result;
		}*/
		// 发送通知
		t_company_info company_info = companyInfoService
				.findByUserId(dcp.lender_id);
		if (company_info == null) {
			result.code = -1;
			result.msg = "放款人查询异常";
			return result;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("user_name", company_info.full_name);
		param.put("bill_code", dcp.certificate_code + "数字");
		noticeService.sendSysNotice(company_info.user_id,
				NoticeScene.COLLECTION_AFFIRM, param);
		
		//TODO
		
		result.code = 2;
		result.msg = "托收成功！";
		return result;

	}

	/**
	 * 确认划款
	 * 
	 * @param id
	 *            数字凭证id
	 * @param user_id
	 *            用户id
	 * @return
	 * @author xiaojun
	 * @version 2017-8-3
	 */
	public ResultInfo confirmTransfer(long id, long user_id) {
		ResultInfo result = new ResultInfo();
		t_digital_commercial_paper dcp = findByID(id);

		if (dcp == null) {
			result.code = -1;
			result.msg = "查询数字凭证信息失败！";
			return result;
		}
		if (user_id != dcp.receive_id) {
			result.code = -1;
			result.msg = "警告！不是收票人不能操作！";
			return result;
		}
		if (dcp.digital_com_status != DigitalStatus.REPAYMENT.code) {
			result.code = -1;
			result.msg = "状态非法！";
			return result;
		}

		t_commercial_paper_info cpi = commerciaPaperiInfoService
				.findByID(dcp.commer_paper_id);
		if (null == cpi) {
			result.code = -1;
			result.msg = "商票信息异常！";
			return result;
		}
		int i = commerciaPaperiInfoService.upPaperStatus(
				TicketStatus.ALL_SQUARED.code, 0, cpi.id);
		if (i < 0) {
			result.code = -1;
			result.msg = "商票状态更新失败！";
			return result;
		}
		boolean upStatus = updateStatus(DigitalStatus.LOSE_EFFICACY.code,
				DigitalStatus.REPAYMENT.code, id);
		if (!upStatus) {
			result.code = -1;
			result.msg = "数字凭证状态更新失败！";
			return result;
		}
//		//开票人额度
//		t_user_credit user_credit = userCreditService.findByID(dcp.company_credit_id) ;
//		user_credit.cleared_limit += dcp.digital_com_paper_money ; 
//		
//		if(user_credit.id == dcp.credit_limit_id){
//			user_credit.transferee_limit += dcp.digital_com_paper_money;
//		}
//		user_credit.usable_limit += dcp.digital_com_paper_money;
//		boolean save= userCreditService.save(user_credit);
//		if(!save){
//			result.code=-1;
//			result.msg="开票人额度更新失败！";
//			return result;
//		}
		// 收票人额度变化
//		t_user_credit userCredit = userCreditService
//				.findByID(dcp.receive_credit_id);
//		userCredit.cleared_limit += dcp.digital_com_paper_money;
//		userCredit.usable_limit -= dcp.digital_com_paper_money;
//		boolean save = userCreditService.save(userCredit);
//		if (!save) {
//			result.code = -1;
//			result.msg = "收票人额度更新失败！";
//			return result;
//		}
		//添加开票人额度明细表信息
//		String service_order_no = OrderNoUtil.getNormalOrderNo(ServiceType.TICKET_CASH, "");
//		t_user_credit_detail amountDetail=new t_user_credit_detail(new Date(),dcp.company_id,dcp.drawer,dcp.digital_com_paper_money,user_credit.credit_granting_code,user_credit.start_time,user_credit.end_time,user_credit.lender_id,user_credit.lender_name,0,0,0,dcp.digital_com_paper_money,0,user_credit.usable_limit,service_order_no,ServiceType.TICKET_CASH.value,cpi.receive_credit_id,dcp.receive_id);
//		boolean saveDetail= userCreditDetailService.save(amountDetail);
//		if(!saveDetail){
//			LoggerUtil.error(false,"新增开票人额度明细异常");
//			result.code=-1;
//			result.msg="新增额度明细异常";
//			return result;
//		}
		// 添加收票人额度明细表信息
//		String service_order_no = OrderNoUtil.getNormalOrderNo(
//				ServiceType.COLLECTION_SUCCESS, "");
//		t_user_credit_detail amountDetail = new t_user_credit_detail(new Date(), dcp.receive_id,
//				dcp.receive_person, 0,
//				userCredit.credit_granting_code, userCredit.start_time,
//				userCredit.end_time, userCredit.lender_id,
//				userCredit.lender_name, 0, 0, 0, dcp.digital_com_paper_money,
//				0, -dcp.digital_com_paper_money, service_order_no,
//				ServiceType.COLLECTION_SUCCESS.value, cpi.receive_credit_id,
//				0);
//		boolean saveDetail = userCreditDetailService.save(amountDetail);
//		if (!saveDetail) {
//			LoggerUtil.error(false, "新增收票人额度明细异常");
//			result.code = -1;
//			result.msg = "新增额度明细异常";
//			return result;
//		}

		// 发送通知
		/*
		 * t_company_info company_info = companyInfoService.(dcp.lender_id);
		 * if(company_info == null){ result.code = -1; result.msg =
		 * "债权剩余金额更新异常"; return result; } Map<String, Object> param = new
		 * HashMap<String, Object>();
		 * param.put("user_name",company_info.full_name);
		 * param.put("bill_code",dcp.certificate_code+"数字");
		 * noticeService.sendSysNotice(company_info.user_id,
		 * NoticeScene.COLLECTION_AFFIRM, param);
		 */
		 t_company_info company_info = companyInfoService.findByID(dcp.lender_id); 
		  if(company_info == null){
			  result.code = -1;
			  result.msg = "获取放款人信息失败"; 
			  return result; 
		  }
		  Map<String, Object> param = new HashMap<String, Object>();
		  param.put("user_name",company_info.full_name);
		  param.put("full_name",dcp.receive_person);
		  param.put("bill_code",cpi.bill_code);
		  noticeService.sendSysNotice(company_info.user_id,  NoticeScene.CONFIRM_TRANSFER, param);
		result.code = 1;
		result.msg = "确认成功！";
		return result;

	}

	/***
	 * 前台- 账户中心- 交易管理-数字凭证-开出（收到）的数字凭证
	 * 
	 * @param showType
	 *            0 待确认 1 已确认 2 已拒收 3 已到期 4 已逾期 5 已失效 6 已撤销 7 质押中 8 已背书 9 已还款
	 * @param type
	 *            0 开出的数字凭证 1 收到的数字凭证
	 * @param currPage
	 * @param pageSize
	 * @param exports
	 *            导出
	 * @param user_id
	 *            用户id
	 * @param checkin_time
	 *            开始时间
	 * @param to_checkin_time
	 *            结束时间
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */

	public PageBean<t_digital_commercial_paper> pageOfDigitalTicketList(
			int showType, int type, int currPage, int pageSize, int exports,
			long user_id, String checkin_time, String to_checkin_time) {
		return digitalCommercialPaperDao.pageOfDigitalTicketList(showType,
				type, currPage, pageSize, exports, user_id, checkin_time,
				to_checkin_time);
	}

	/**
	 * 前台- 账户中心- 交易管理-数字凭证--金额计算
	 * 
	 * @param showType
	 *            状态 0 所有 1 待确认 2 已确认 3 已拒收 4 已到期 5 已逾期 6 已失效 7 已撤销 8 质押中 9 已背书
	 * @param type
	 *            0 开出的数字凭证 1 收到的数字凭证
	 * @param currPage
	 * @param pageSize
	 * @param money
	 *            要计算的金额字段
	 * @param user_id
	 *            用户id
	 * @param checkin_time
	 *            开始时间
	 * @param to_checkin_time
	 *            结束时间
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */
	public double DigitalTicketAmount(int showType, int type, String money,
			long user_id, String checkin_time, String to_checkin_time) {
		return digitalCommercialPaperDao.DigitalTicketAmount(showType, type,
				money, user_id, checkin_time, to_checkin_time);
	}

	/**
	 * 解冻商票到期还款金额
	 * 
	 * @param bill_code
	 *            商票号码
	 * @param userId
	 * @param bail
	 *            解冻的金额
	 * @param res
	 * 
	 * @author xiaojun
	 * @createDate 2017年5月19日
	 */

	public ResultInfo unfreezeTicketAmount(String serviceOrderNo,
			String bill_code, long userId, double paper_money) {
		ResultInfo result = new ResultInfo();

		boolean fundSignChecked = true; // 资金签名是否通过
		result = userFundService.userFundSignCheck(userId);
		if (result.code < 1) {
			fundSignChecked = false;
		}

		boolean unFreeze = userFundService
				.userFundUnFreeze(userId, paper_money);
		if (!unFreeze) {
			result.code = -1;
			result.msg = "解冻用户资金失败";

			return result;
		}
		if (fundSignChecked) {
			result = userFundService.userFundSignUpdate(userId);
			if (result.code < 1) {

				return result;
			}
		}
		t_user_fund tuf = userFundService.queryUserFundByUserId(userId);

		/** 添加交易记录 */
		tuf = userFundService.queryUserFundByUserId(tuf.user_id);
		Map<String, String> params = new HashMap<String, String>();
		params.put("bill_code", bill_code);
		boolean minusFund = dealuserservice.addDealUserInfo(serviceOrderNo,
				tuf.user_id, paper_money, tuf.balance, tuf.freeze,
				t_deal_user.OperationType.TICKET_AMOUNT_UNFREEZE, params);
		if (!minusFund) {
			result.code = -1;
			result.msg = "解冻到期商票资金失败!";

			return result;
		}

		/** 发送邮件、站内信、短信通知用户 */
		Map<String, Object> content = new HashMap<String, Object>();
		content.put("user_name", tuf.name);
		content.put("bill_code", bill_code);
		content.put("paper_money", paper_money);

		noticeservice.sendSysNotice(tuf.user_id,
				NoticeScene.TICKET_AMOUNT_UNFREEZE, content);

		result.code = 1;
		result.msg = "解冻到期商票资金成功";
		return result;
	}

	/**
	 * 托收
	 * 
	 * @param id
	 * @param serviceOrderNo
	 * @return
	 * @author xiaojun
	 * @version 2017-5-19
	 */
	public ResultInfo collection(long id, String serviceOrderNo, long user_id) {
		ResultInfo result = new ResultInfo();
		t_digital_commercial_paper dcp = findByID(id);
		if (dcp == null) {
			result.code = -1;
			result.msg = "查询数字凭证信息失败！";
			return result;
		}
		if (user_id != dcp.receive_id) {
			result.code = -1;
			result.msg = "警告！不是收票人不能托收！";
			return result;
		}
		result = unfreezeTicketAmount(serviceOrderNo, dcp.certificate_code,
				dcp.receive_id, dcp.account_frozen);

		if (result.code < 0) {
			return result;
		}
		result.code = 1;
		result.msg = "托收成功！请到用户余额中查看";
		return result;
	}

	/**
	 * 追索通知
	 * 
	 * @param id
	 * @param type
	 * @return
	 * @author xiaojun
	 * @version 2017-8-3
	 */
	public ResultInfo recourseToInform(long id, int type) {
		ResultInfo result = new ResultInfo();
		Map<String, Object> content = new HashMap<String, Object>();
		boolean save = false;
		if (type == 0) {
			t_digital_commercial_paper dcp = findByID(id);
			if (dcp == null) {
				result.code = -1;
				result.msg = "参数有误，请确认后再操作！";
				return result;
			}
			if (dcp.digital_com_status == DigitalStatus.OVERDUE.code) {
				content.put("user_name", dcp.drawer);// 开票人
				content.put("xxx", dcp.receive_person);// 收票人
				content.put("bill_code", dcp.certificate_code);// 凭证号码
				content.put("paper_money", dcp.digital_com_paper_money);// 凭证金额
				save = noticeservice.sendSysNotice(dcp.company_id,
						NoticeScene.RECOURSE_TO_INFORM, content);
			} else {
				result.code = -1;
				result.msg = "状态非法！";
				return result;
			}
		} else if (type == 1) {
			t_endorse endorse = endorseService.findByID(id);
			if (endorse == null) {
				result.code = -1;
				result.msg = "参数有误，请确认后再操作！";
				return result;
			}
			if (endorse.receive_endorse_status == DigitalStatus.OVERDUE.code) {
				t_digital_commercial_paper dcp = findByID(endorse.digital_id);
				content.put("user_name", endorse.endorse_company_name);// 背书公司名称
				content.put("xxx", endorse.endoresd_company_name);// 被背书公司名称
				content.put("bill_code", dcp.certificate_code);// 凭证号码
				content.put("paper_money", endorse.bill_money);// 凭证金额
				save = noticeservice.sendSysNotice(dcp.company_id,
						NoticeScene.RECOURSE_TO_INFORM, content);
			} else {
				result.code = -1;
				result.msg = "状态非法！";
				return result;
			}
		} else if (type == 2) {

		}
		if (!save) {
			LoggerUtil.error(true, "发送追索通知失败");
			result.code = -1;
			result.msg = "发送追索通知失败";
			return result;
		}
		result.code = 1;
		result.msg = "发送追索通知成功";
		return result;
	}

	/**
	 * 拒付
	 * 
	 * @param id
	 *            数字凭证id
	 * @return
	 * @author xiaojun
	 * @version 2017-8-3
	 */
	public ResultInfo dishonour(long id) {
		ResultInfo result = new ResultInfo();
		t_digital_commercial_paper dcp = findByID(id);
		t_commercial_paper_info cpi = commerciaPaperiInfoService
				.findByID(dcp.original_id);
		if (dcp.digital_com_status != DigitalStatus.EXPIRE.code) {
			result.code = -1;
			result.msg = "拒付数字凭证状态异常";
			return result;
		}
		cpi.collection_status = 2;
		cpi = commerciaPaperiInfoService.addTicket(cpi);
		if (cpi == null) {
			result.code = -1;
			result.msg = "商票拒付状态更新失败！";
			return result;
		}
		result.code = 1;
		result.msg = "拒付成功！";
		return result;
	}

	/**
	 * 数字凭证还款（准备）
	 * 
	 * @param userId
	 *            用户ID
	 * @param
	 * @return
	 * 
	 * @author xiaojun
	 * @createDate 2015年12月28日
	 */
	public ResultInfo normalRepayment(long userId,
			t_digital_commercial_paper dcp) {
		ResultInfo result = new ResultInfo();

		if (dcp == null) {
			throw new InvalidParameterException(
					"t_digital_commercial_paper is null");
		}

		t_user_fund userFund = userFundService.queryUserFundByUserId(userId);

		if (userFund == null) {
			result.code = -1;
			result.msg = "获取用户资金信息失败";

			return result;
		}

		/** 用户资金是否出现异常变动 */
		result = userFundService.userFundSignCheck(userId);
		if (result.code < 1) {

			return result;
		}

		/** 借款人资金是否充足 */
		double payAmt = dcp.digital_com_paper_money;
		if (userFund.balance < payAmt) {
			result.code = -4;
			result.msg = "余额不足";

			return result;
		}
		result.code = 1;
		result.msg = "还款准备完毕";
		return result;
	}

	/**
	 * 确认还款（执行）
	 * 
	 * @param billId
	 *            数字凭证ID
	 * @param serviceOrderNo
	 *            业务订单号
	 * @return
	 * 
	 * @author xiaojun
	 * @createDate 2017年5月23日
	 */
	public ResultInfo doRepayment(long billId, String serviceOrderNo) {
		ResultInfo result = new ResultInfo();

		t_digital_commercial_paper dcp = findByID(billId);
		if (dcp == null) {
			result.code = -1;
			result.msg = "该数字凭证不存在";

			return result;
		}

		// 查询商票持票人
		t_commercial_paper_info cpi = commerciaPaperiInfoService
				.findByID(dcp.original_id);
		// 持票人应收金额
		double receiveAmt = cpi.paper_money;

		boolean isSignSuccess = true;
		/*
		 * t_commercial_paper_lines commercial_paper_lines=null;
		 * if(cpi.receive_id==0){
		 * commercial_paper_lines=commerciaPaperLinesService
		 * .findByColumn(" commer_paper_id=? AND comer_paper_status IN(?,?)",
		 * cpi.id,PaperStatus.EXPIRE.code,PaperStatus.OVERDUE.code);
		 * 
		 * if(commercial_paper_lines==null){ result.code=-1;
		 * result.msg="查找额度信息失败"; return result; }
		 * commercial_paper_lines.comer_paper_status
		 * =PaperStatus.LOSE_EFFICACY.code; boolean save=
		 * commerciaPaperLinesService
		 * .saveCommercialPaper(commercial_paper_lines); if(!save){
		 * result.code=-1; result.msg="更新额度状态失败"; return result; }
		 * cpi.receive_id = commercial_paper_lines.user_id; }
		 */
		// 用户签名是否通过
		result = userFundService.userFundSignCheck(cpi.receive_id);
		if (result.code < 1) {
			isSignSuccess = false;
		}

		boolean addFund = userFundService.userFundAdd(cpi.receive_id,
				receiveAmt);
		if (!addFund) {
			result.code = -1;
			result.msg = "增加持票人可用余额失败";
			return result;
		}
		/*
		 * if(commercial_paper_lines!=null &&
		 * commercial_paper_lines.finacing_used_limit>0 ){ // 冻结用户已用额度金额 addFund
		 * = userFundService.userFundFreeze(commercial_paper_lines.user_id,
		 * commercial_paper_lines.finacing_used_limit); if (!addFund) {
		 * result.code = -1; result.msg = "冻结用户已用额度金额失败"; return result; } }
		 */

		// 刷新持票人资金信息
		t_user_fund investUserFund = userFundService
				.queryUserFundByUserId(cpi.receive_id);
		if (investUserFund == null) {
			result.code = -1;
			result.msg = "获取持票人资金信息失败";

			return result;
		}

		// 如果投资用户账户资金没有遭到非法改动，那么就更新其篡改标志，否则不更新
		if (isSignSuccess) {
			userFundService.userFundSignUpdate(cpi.receive_id);
		}

		// 添加持票人收款记录
		Map<String, String> summaryParam = new HashMap<String, String>();
		summaryParam.put("bill_code", cpi.bill_code);
		/*boolean addDeal = dealUserService.addDealUserInfo(serviceOrderNo,
				cpi.receive_id, cpi.paper_money,
				investUserFund.balance, // 此时不计“投资服务费”和“逾期罚息”
				investUserFund.freeze, t_deal_user.OperationType.DUE_PAYMENT,
				summaryParam);
		if (!addDeal) {
			result.code = -1;
			result.msg = "添加持票人收款记录失败";

			return result;
		}*/

		// 通知持票人
		Map<String, Object> sceneParame = new HashMap<String, Object>();
		sceneParame.put("user_name", investUserFund.name);
		sceneParame.put("bill_code", cpi.bill_code);
		sceneParame.put("paper_money", receiveAmt);
		noticeservice.sendSysNotice(cpi.receive_id, NoticeScene.DUE_PAYMENT,
				sceneParame);

		// 用户签名是否通过
		result = userFundService.userFundSignCheck(dcp.company_id);
		if (result.code < 1) {
			isSignSuccess = false;
		}
		/** 扣除开票人还款金额 */
		double repayAmt = cpi.paper_money;
		boolean minusFund = userFundService.userFundMinus(dcp.company_id,
				repayAmt);
		if (!minusFund) {
			result.code = -1;
			result.msg = "扣除开票人可用余额失败";

			return result;
		}

		// 更新借款人资产签名更新
		userFundService.userFundSignUpdate(dcp.company_id);

		// 刷新借款人资金信息
		t_user_fund loanUserFund = userFundService
				.queryUserFundByUserId(dcp.company_id);
		if (loanUserFund == null) {
			result.code = -1;
			result.msg = "获取开票人资金信息失败";

			return result;
		}

		// 添加开票人还款记录
		summaryParam = new HashMap<String, String>();
		summaryParam.put("bill_code", cpi.bill_code);
		/*addDeal = dealUserService.addDealUserInfo(serviceOrderNo,
				dcp.company_id, cpi.paper_money, loanUserFund.balance,
				loanUserFund.freeze,
				t_deal_user.OperationType.EXPIRE_REIMBURSEMENT, summaryParam);
		if (!addDeal) {
			result.code = -1;
			result.msg = "添加开票人还款记录失败";
			return result;
		}*/
		// 通知借款人
		sceneParame = new HashMap<String, Object>();
		sceneParame.put("user_name", loanUserFund.name);
		sceneParame.put("bill_code", cpi.bill_code);
		sceneParame.put("paper_money", receiveAmt);
		noticeservice.sendSysNotice(dcp.company_id,
				NoticeScene.EXPIRE_REIMBURSEMENT, sceneParame);
		result.code = 1;
		result.msg = "还款成功";
		return result;
	}

	/**
	 * 确认托收状态更新
	 * 
	 * @param id
	 *            数字凭证id
	 * @return
	 * @author xiaojun
	 * @version 2017-5-23
	 */
	public ResultInfo stateChange(long id, int olStatus) {
		ResultInfo result = new ResultInfo();
		t_digital_commercial_paper dcp = findByID(id);
		// 更新数字凭证状态
		boolean save = updateStatus(DigitalStatus.LOSE_EFFICACY.code, olStatus,
				id, 1, dcp.is_endorse);
		if (!save) {
			result.code = -1;
			result.msg = "数字凭证状态更新失败";
		}
		// 更新商票状态
		t_commercial_paper_info cpi = commerciaPaperiInfoService
				.findByID(dcp.original_id);
		/*
		 * t_commercial_paper_lines commercial_paper_lines=null;
		 * if(cpi.receive_id==0){ try { commercial_paper_lines =
		 * commerciaPaperLinesService
		 * .findByColumn(" commer_paper_id=? AND comer_paper_status IN(?,?)",
		 * cpi.id,PaperStatus.EXPIRE.code,PaperStatus.OVERDUE.code);
		 * 
		 * } catch (Exception e) { result.code=-1; result.msg="查询额度信息失败"; return
		 * result; }
		 * 
		 * }
		 */

		cpi.cash_all_amount = dcp.digital_com_paper_money;
		cpi.cash_amount = dcp.digital_com_paper_money;
		cpi.cash_time = new Date();
		cpi.paper_pic_under = ImgUtil.screenshot(dcp, 5, cpi, null);
		cpi.paper_status = t_commercial_paper_info.TicketStatus.ALL_SQUARED.code;
		cpi.repayment_status = 1;
		cpi = commerciaPaperiInfoService.addTicket(cpi);
		if (cpi == null) {
			result.code = -1;
			result.msg = "商票状态更新失败";
			return result;
		}

		// 如果背书出去 需要修改背书状态
		if (dcp.is_endorse == 1) {
			t_endorse endorse = endorseService.findByColumn(
					"certificate_code=?", cpi.certificate_code);
			endorse.receive_endorse_status = DigitalStatus.LOSE_EFFICACY.code;
			endorse.repayment_status = 1;
			save = endorseService.saveEndorse(endorse);
			if (!save) {
				result.code = -1;
				result.msg = "背书状态更新失败";
				return result;
			}
		}
		/*
		 * // 修改额度表数据 t_commercial_paper_lines
		 * cpl=commerciaPaperLinesService.findByID(dcp.credit_limit_id);
		 * cpl.finacing_available_limit+=cpi.paper_money;
		 * cpl.finacing_used_limit-=cpi.paper_money; save=
		 * commerciaPaperLinesService.saveCommercialPaper(cpl); if(!save){
		 * result.code=-1; result.msg="更新额度失败"; return result; }
		 */
		/*
		 * // 添加额度明细表信息 t_amount_detail amountDetail=new
		 * t_amount_detail(dcp.credit_limit_id,dcp.receive_person,new
		 * Date(),dcp.digital_com_paper_money,cpl.finacing_available_limit
		 * ,CrawlType
		 * .CONFIRM_PAYMENT.code,dcp.contract_name_code,cpl.finacing_total_limit
		 * ); boolean saveDetail=
		 * amountDetailService.saveAmountDetail(amountDetail); if(!saveDetail){
		 * result.code=-1; result.msg="新增额度明细异常"; return result; }
		 */
		return result;

	}

	/**
	 * 定时任务 标记数字凭证到期
	 * 
	 * @return
	 * @author xiaojun
	 * @version 2017-5-24
	 */
	public ResultInfo systemMarkDigitTicketExpire() {
		ResultInfo result = new ResultInfo();
		// 将到期的待签收背书流转强制撤回
//		result = endorseService.autocancelEndorse();
//		if (result.code < 0) {
//			return result;
//		}
		// 将到期的待签收数字凭证强制撤回
		result = autocancelDigital();
		/*if (result.code < 0) {
			return result;
		}*/

		return digitalCommercialPaperDao.autoMarkDigitTicketExpire();
	}

	/**
	 * 定时任务 标记数字凭证逾期
	 * 
	 * @return
	 * @author xiaojun
	 * @version 2017-5-24
	 */
	public ResultInfo systemMarkDigitTicketOverdue() {
		return digitalCommercialPaperDao.autoMarkDigitTicketOverdue();
	}

	/**
	 * 定时任务-数字到期自动兑现
	 * 
	 * @return
	 * @author xiaojun
	 * @version 2017-5-24
	 */
	public ResultInfo systemDigitTicketExpireCash() {
		ResultInfo result = new ResultInfo();
		// 查出到期的质押商票
		List<t_digital_commercial_paper> list = digitalCommercialPaperDao
				.findAutoCashDigitTicketExpire(DigitalStatus.EXPIRE.code);
		if (list == null || list.size() == 0) {
			result.code = 1;
			result.msg = "没有数字凭证到期";
			return result;
		}
		for (int i = 0; i < list.size(); i++) {
			t_digital_commercial_paper dcp = list.get(i);
			result.msg = "原商票没有兑现";
			// 查询原商票是否兑现
			/*
			 * t_commercial_paper_lines
			 * cpl=commerciaPaperLinesService.findByID(dcp.credit_limit_id);
			 * t_commercial_paper_info
			 * oldcpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
			 * if(oldcpi.cash_all_amount==cpl.finacing_total_limit &&
			 * oldcpi.paper_status==TicketStatus.ALL_SQUARED.code){
			 * t_commercial_paper_info
			 * cpi=commerciaPaperiInfoService.findByID(dcp.original_id); //
			 * 更新商票的状态为：已结清 cpi.paper_status=TicketStatus.ALL_SQUARED.code;
			 * cpi.cash_all_amount=dcp.digital_com_paper_money;
			 * cpi.cash_amount=dcp.digital_com_paper_money;
			 * cpi.collection_status=1; cpi.repayment_status=1;
			 * cpi=commerciaPaperiInfoService.addTicket(cpi); if(cpi==null){
			 * result.code=-1; result.msg="商票状态更新失败"; return result; }
			 * if(dcp.is_endorse==1){ t_endorse endorse =
			 * endorseService.findByColumn("certificate_code=?",
			 * cpi.certificate_code);
			 * endorse.receive_endorse_status=DigitalStatus.REPAYMENT.code;
			 * if(!endorseService.saveEndorse(endorse)){ result.code=-1;
			 * result.msg="背书状态更新失败"; return result; } } // 订单号 String
			 * serviceOrderNo =
			 * OrderNoUtil.getNormalOrderNo(ServiceType.TICKET_CASH
			 * ,OrderNoUtil.COMMERICAL_ORDER_NORMAL); result =
			 * doAutoCash(dcp.id, serviceOrderNo); if (result.code < 0) {
			 * result.code=-1; result.msg="自动兑换商票金额失败"; return result; } }
			 */
		}

		result.code = 1;
		return result;
	}

	/**
	 * 将到期的待签收流转强制撤回
	 * 
	 * @return
	 * @author xiaojun
	 * @version 2017-6-29
	 */

	public ResultInfo autocancelDigital() {
		
		ResultInfo result = new ResultInfo();
		List<t_digital_commercial_paper> digitalList = digitalCommercialPaperDao
				.autocancelDigital();
		/* 关闭自动事务 */
		JPAPlugin.closeTx(false);
		if (digitalList != null && digitalList.size() > 0) {
			for (int i = 0; i < digitalList.size(); i++) {
				/* 开启自动事务 */
				JPAPlugin.startTx(false);
				t_digital_commercial_paper endorse = digitalList.get(i);
				result = cancelDigital(endorse.id, 0);
				if (result.code < 0) {
					LoggerUtil.error(true, result.msg);
				}
				/* 关闭自动事务 */
				JPAPlugin.closeTx(false);
				
			}
		}
		/* 开启自动事务 */
		JPAPlugin.startTx(false);
		return result;

	}

	/**
	 * 数字凭证-撤票(拒收)
	 * 
	 * @param id
	 *            数字凭证表的id
	 * @param type
	 *            0 撤销 1 拒收
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */
	public ResultInfo cancelDigital(long id, int type) {
		ResultInfo result = new ResultInfo();
		t_digital_commercial_paper digital_commercial_paper = findByID(id);
		t_creditor_right_debt crd = creditorRightDebtService
				.findByID(digital_commercial_paper.debt_creditor_id);
		if (digital_commercial_paper.digital_com_status != DigitalStatus.TBC.code) {
			result.code = -1;
			result.msg = "状态非法！";
			return result;
		}
		// 更新债权债务表的剩余额度数据
		crd.rest_debt_money += digital_commercial_paper.digital_com_paper_money;
		crd.status = t_creditor_right_debt.CreditorRightDebtStatus.CONFIRM.code;
		boolean save = creditorRightDebtService.addCreditorRightDebt(crd);
		if (!save) {
			LoggerUtil.error(true, "债权剩余金额更新异常");
			result.code = -1;
			result.msg = "债权剩余金额更新异常";
			return result;
		}
		// 修改数字凭证状态为已撤销
		if (type == 0) {
			digital_commercial_paper.digital_com_status = t_digital_commercial_paper.DigitalStatus.REVOCATION.code;
		} else if (type == 1) {
			digital_commercial_paper.digital_com_status = t_digital_commercial_paper.DigitalStatus.REJECTION.code;
		}
		digital_commercial_paper = saveDigitalPapre(digital_commercial_paper);
		if (digital_commercial_paper == null) {
			LoggerUtil.error(true, "更新数字凭证状态异常");
			result.code = -1;
			result.msg = "更新数字凭证状态异常";
			return result;
		}
		// 修改商票已撤销
		t_commercial_paper_info cpi = commerciaPaperiInfoService
				.findByID(digital_commercial_paper.commer_paper_id);
		cpi.paper_status = t_commercial_paper_info.TicketStatus.REVOCATION.code;
		cpi = commerciaPaperiInfoService.addTicket(cpi);
		if (cpi == null) {
			LoggerUtil.error(true, "更新商票状态异常");
			result.code = -1;
			result.msg = "更新商票状态异常";
			return result;
		}

		// 更新开票人额度信息
		t_user_credit user_credit = userCreditService
				.findByID(digital_commercial_paper.company_credit_id);
		double paper_money = digital_commercial_paper.digital_com_paper_money;
		user_credit.usable_limit += paper_money;
		user_credit.transfer_used_limit -= paper_money;
		boolean saveCredit = userCreditService.save(user_credit);
		if (!saveCredit) {
			LoggerUtil.error(false, "更新开票人授信额度异常");
			result.code = -1;
			result.msg = "更新开票人授信额度异常";
			return result;
		}
		
		//减少收票人的额度信息
		t_user_credit userCredit = userCreditService
				.findByID(digital_commercial_paper.receive_credit_id);
		userCredit.usable_limit -= paper_money;
		userCredit.transfer_used_limit += paper_money;
		saveCredit = userCreditService.save(userCredit);
		if (!saveCredit) {
			LoggerUtil.error(false, "更新收票人授信额度异常");
			result.code = -1;
			result.msg = "更新收票人授信额度异常";
			return result;
		}
		
		// 获取上一级商票的信息
		t_commercial_paper_info orgcpi = commerciaPaperiInfoService
				.findByID(digital_commercial_paper.original_id);
		
		//如果存在上一级商票，增加其可用余额
		if (orgcpi != null) {
			orgcpi.finacing_residue_limit += paper_money;
			boolean flag = commerciaPaperiInfoService.save(orgcpi);
			if(!flag){
				LoggerUtil.error(false, "更新商票额度异常");
				result.code = -1;
				result.msg = "更新上一级额度异常";
				return result;
			}
		}
		
		// 添加开票人额度明细表信息
		String service_order_no = OrderNoUtil.getNormalOrderNo(
				ServiceType.TICKET_AVERT, "");
		t_user_credit_detail amountDetail = new t_user_credit_detail(
				new Date(), digital_commercial_paper.company_id,
				digital_commercial_paper.drawer, 0,
				user_credit.credit_granting_code, user_credit.start_time,
				user_credit.end_time, user_credit.lender_id,
				user_credit.lender_name, 0, 0, paper_money, 0, 0,
				paper_money, service_order_no,
				ServiceType.CREDIT_BACK.value, cpi.receive_credit_id,
				0);
		boolean saveDetail = userCreditDetailService.save(amountDetail);
		if (!saveDetail) {
			LoggerUtil.error(false, "新增开票人额度明细异常");
			result.code = -1;
			result.msg = "新增额度明细异常";
			return result;
		}
		
		//TODO
		// 收票人额度明细表信息
		service_order_no = OrderNoUtil.getNormalOrderNo(
				ServiceType.TICKET_AVERT, "");
		t_user_credit_detail amount = new t_user_credit_detail(
				new Date(), digital_commercial_paper.receive_id,
				digital_commercial_paper.receive_person, 0,
				userCredit.credit_granting_code, userCredit.start_time,
				userCredit.end_time, userCredit.lender_id,
				userCredit.lender_name, 0, paper_money, 0, 0, 0,
				-paper_money, service_order_no,
				ServiceType.CREDIT_BACK.value, cpi.receive_credit_id,
				0);
		saveDetail = userCreditDetailService.save(amount);
		if (!saveDetail) {
			LoggerUtil.error(false, "新增开票人额度明细异常");
			result.code = -1;
			result.msg = "新增额度明细异常";
			return result;
		}

		// 商票类型
		int isDigital = 1;
		if(orgcpi == null){
			isDigital = 0;
		}

		// 商票到期日期
		Date paperExpireTime = digital_commercial_paper.payment_time;

		// 登记时间
		Date time = digital_commercial_paper.pledge_current_time;
		
		if(time.compareTo(paperExpireTime)!=-1){
			result.code = -1;
			result.msg = "开票的日期不能大于商票的截止日期";
			return result;
		}

		// 两个日期相隔的天数
		int dateCount = DateUtil.getDaysDiffCeil(time, paperExpireTime);

		/*double custodian_fee = Arith.div(Arith.mul(
				Arith.mul(paper_money, user_credit.custodian_fee), dateCount),
				Arith.mul(30, 100), 2);*/
		double custodian_fee = FeeCalculateUtil.getTransfer(paper_money, time, paperExpireTime, user_credit.custodian_fee);
		
		// 票信流转服务费费率
		double fee = Double.valueOf(settingService
				.findSettingValueByKey(SettingKey.CUSTODIAN_FEE));
		
		//票信流转服务费
		double leader_custodian_fee = FeeCalculateUtil.getTransfer(paper_money,time , paperExpireTime, fee);

		
		//如果开票人使用的不是初始授信
		if (user_credit.parent_id != 0 && custodian_fee > 0) {

			// 解冻流转金额保管费,
			boolean saveFreeze = userFundService.userFundUnFreeze(
					digital_commercial_paper.company_id, custodian_fee);
			if (!saveFreeze) {
				result.code = -1;
				result.msg = "解冻票信额度管理费失败";
				return result;
			}
			t_user_fund userFund = userFundService
					.queryUserFundByUserId(digital_commercial_paper.company_id);
			String serviceOrderNo = OrderNoUtil.getNormalOrderNo(
					ServiceType.USER_UNFREEZE, "");
			/** 添加用户交易记录 */
			Map<String, String> summaryPrams = new HashMap<String, String>();
			summaryPrams.put("amount", custodian_fee + "");
			summaryPrams.put("certificate_code", digital_commercial_paper.certificate_code);
			boolean addDeal = dealUserService.addDealUserInfo(
					serviceOrderNo, // 订单号
					digital_commercial_paper.company_id, custodian_fee,
					userFund.balance, userFund.freeze,
					t_deal_user.OperationType.CUSTODIAN_FEE_UNFREEZE,
					summaryPrams);

			if (!addDeal) {
				result.code = -1;
				result.msg = "添加交易记录失败！";
				return result;
			}
		}
		//如果开票人使用的不是初始授信
		if (user_credit.parent_id != 0 && leader_custodian_fee > 0) {
			
			// 解冻票信流转服务费,
			boolean saveFreeze = userFundService.userFundUnFreeze(
					user_credit.lender_id, leader_custodian_fee);
			if (!saveFreeze) {
				result.code = -1;
				result.msg = "解冻票信流转服务费失败";
				return result;
			}
			t_user_fund userFund = userFundService
					.queryUserFundByUserId(digital_commercial_paper.lender_id);
			String serviceOrderNo = OrderNoUtil.getNormalOrderNo(
					ServiceType.USER_UNFREEZE, "");
			/** 添加用户交易记录 */
			Map<String, String> summaryPrams = new HashMap<String, String>();
			summaryPrams.put("certificate_code", digital_commercial_paper.certificate_code);
			summaryPrams.put("amount", leader_custodian_fee + "");
			boolean addDeal = dealUserService.addDealUserInfo(
					serviceOrderNo, // 订单号
					user_credit.lender_id, leader_custodian_fee,
					userFund.balance, userFund.freeze,
					t_deal_user.OperationType.UNFREEZE_FETCH_PAY_PLAT_CREDIT,
					summaryPrams);
			
			if (!addDeal) {
				result.code = -1;
				result.msg = "添加交易记录失败！";
				return result;
			}
		}
		t_company_info company_info = null;
		if (type == 0) {
			company_info = companyInfoService
					.findByUserId(digital_commercial_paper.receive_id);
		} else {
			company_info = companyInfoService
					.findByUserId(digital_commercial_paper.company_id);
		}
		if (company_info == null) {
			result.code = -1;
			result.msg = "企业信息异常";
			return result;
		}
		// 发送通知
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("user_name", company_info.full_name);
		param.put("drawee", digital_commercial_paper.drawer);
		param.put("certificate_code", digital_commercial_paper.certificate_code);
		param.put("status", digital_commercial_paper.getStatus().value);
		noticeService.sendSysNotice(company_info.user_id,
				NoticeScene.OPEN_TIOCKET_AFFIRM_NO, param);

		result.code = 1;
		result.msg = "操作成功！状态更新为：" + digital_commercial_paper.getStatus().value;
		return result;
	}

	// /strat------------------------------------------------------
	/**
	 * 更新当前的状态和额度信息
	 * 
	 * @param id
	 * @param amount
	 * @return
	 * @author liaijun
	 * @version 2018年1月19日
	 */
	public int updateDigData(long id, double amount) {
		return digitalCommercialPaperDao.updateDigData(id, amount);
	}

	/**
	 * 流转交易收取费用(授信审核时)
	 * 
	 * @param company_id
	 * @param lender_id
	 * @param amount
	 * @param endMonth 月数
	 * @param serrino
	 * @return
	 * @author xiaojun
	 * @version 2018-1-15
	 */
	public ResultInfo userTransaction(long company_id, long lender_id,
			double credit_amount_submit, int endMonth,
			double custodian_fee_submit, String serrino) {
		ResultInfo result = new ResultInfo();
		
		// 放款额度管理费: 月费率*授信额度*月数
		double custodian_fee = Arith.div(Arith.mul(
				Arith.mul(credit_amount_submit, custodian_fee_submit),
				endMonth), 100, 2);
		
		t_user_fund user_fund = userFundService
				.queryUserFundByUserId(company_id);
		if (user_fund == null) {
			result.code = -1;
			result.msg = "授信申请人用户资金账户异常！！";
			return result;
		}
		if (user_fund.balance < custodian_fee) {
			result.code = 0;
			result.msg = "授信申请人余额不足缴纳票信额度管理费,需充值"+custodian_fee+"元";
			return result;
		}
		// 判断放款人的可用余额是否大于票信流转服务费
		double fee = Double.valueOf(settingService
				.findSettingValueByKey(SettingKey.CUSTODIAN_FEE));
		
		//票信流转服务费
		double leader_custodian_fee = Arith.div(
				Arith.mul(Arith.mul(credit_amount_submit, fee), endMonth),
				100, 2);

		t_user_fund leader_user_fund = userFundService
				.queryUserFundByUserId(lender_id);

		if (leader_user_fund == null) {
			result.code = -1;
			result.msg = "放款人用户资金账户异常！！";
			return result;
		}
		if(Arith.sub(custodian_fee, leader_custodian_fee)<0){
			result.code = -1;
			result.msg = "授信申请人缴纳的票信额度管理费("+custodian_fee+"元)低于放款人缴纳的票信流转服务费("+leader_custodian_fee+"元)，票信额度管理费率应该大于或者等于"+fee+"%";
			return result;
		}
		
		if(custodian_fee>0 && Arith.sub(custodian_fee, leader_custodian_fee)>=0){
			
			// 增加融通人冻结管理费
			Map<String, Object> dealRemarkParamU = new HashMap<String, Object>();
			dealRemarkParamU.put("certificate_code", serrino);
			dealRemarkParamU.put("amount", custodian_fee);
			
			// 收取冻结票信额度管理费失败费(扣除开票用户可用金额)
			boolean saveFreezeU = userFundService.userFundFreeze(company_id,
					custodian_fee);
			if (!saveFreezeU) {
				result.code = -1;
				result.msg = "冻结票信额度管理费失败！";
				return result;
			}
			t_user_fund userFundU = userFundService
					.queryUserFundByUserId(company_id);
			String serviceOrderNoU = OrderNoUtil.getNormalOrderNo(
					ServiceType.USER_UNFREEZE, "");
			/** 添加用户交易记录 */
			Map<String, String> summaryPramsU = new HashMap<String, String>();
			summaryPramsU.put("amount", custodian_fee + "");
			summaryPramsU.put("certificate_code", serrino);
			boolean addDealU = dealUserService.addDealUserInfo(
					serviceOrderNoU, // 订单号
					company_id, custodian_fee, userFundU.balance, userFundU.freeze,
					t_deal_user.OperationType.CUSTODIAN_UNFEE_PAY_CREDIT, summaryPramsU);
			if (!addDealU) {
				result.code = -1;
				result.msg = "添加交易记录失败！";
				return result;
			}
		}
		
		if(custodian_fee>0 && Arith.sub(custodian_fee, leader_custodian_fee)>=0){
			// 收取票信流转费(扣除开票用户冻结金额)
			boolean saveFreeze = userFundService.userFundMinusFreezeAmt(company_id,
					custodian_fee);
			if (!saveFreeze) {
				result.code = -1;
				result.msg = "授信申请人缴纳票信额度管理费失败";
				return result;
			}
			t_user_fund userFund = userFundService
					.queryUserFundByUserId(company_id);
			String serviceOrderNo = OrderNoUtil.getNormalOrderNo(
					ServiceType.USER_TRANSFER, "");
			/** 添加用户交易记录 */
			Map<String, String> summaryPrams = new HashMap<String, String>();
			summaryPrams.put("certificate_code", serrino);
			summaryPrams.put("amount", custodian_fee + "");
			boolean addDeal = dealUserService.addDealUserInfo(
					serviceOrderNo, // 订单号
					company_id, custodian_fee, userFund.balance, userFund.freeze,
					t_deal_user.OperationType.CUSTODIAN_FEE_PAY_CREDIT, summaryPrams);
			
			if (!addDeal) {
				result.code = -1;
				result.msg = "添加交易记录失败！";
				return result;
			}
		}

		if(leader_custodian_fee>0  && custodian_fee > 0 && Arith.sub(custodian_fee, leader_custodian_fee)>=0){
			
			// 收取额度管理服务费(增加放款人用户可用金额)
			boolean saveFreeze = userFundService.userFundAdd(lender_id,
					Arith.sub(custodian_fee, leader_custodian_fee));
			if (!saveFreeze) {
				result.code = -1;
				result.msg = "放款人收取票信额度管理费失败";
				return result;
			}
			t_user_fund lenderUserFund = userFundService
					.queryUserFundByUserId(lender_id);
			String serviceOrderNo = OrderNoUtil.getNormalOrderNo(
					ServiceType.USER_TRANSFER, "");
			/** 添加用户交易记录 */
			Map<String, String> summaryPrams = new HashMap<String, String>();
			summaryPrams.put("certificate_code", serrino);
			summaryPrams.put("amount", custodian_fee + "");
			boolean addDeal = dealUserService.addDealUserInfo(
					serviceOrderNo, // 订单号
					lender_id, custodian_fee, lenderUserFund.balance
					+ leader_custodian_fee, lenderUserFund.freeze,
					t_deal_user.OperationType.CUSTODIAN_FETCH_PAY_CREDIT, summaryPrams);
			
			if (!addDeal) {
				result.code = -1;
				result.msg = "添加交易记录失败！";
				return result;
			}
			
			// 扣除放款人票信流转费
			summaryPrams = new HashMap<String, String>();
			summaryPrams.put("certificate_code", serrino);
			summaryPrams.put("amount", leader_custodian_fee + "");
			addDeal = dealUserService.addDealUserInfo(
					serviceOrderNo, // 订单号
					lender_id, leader_custodian_fee, lenderUserFund.balance,
					lenderUserFund.freeze,
					t_deal_user.OperationType.CUSTODIAN_FETCH_PAY_PLAT_CREDIT, summaryPrams);
			if (!addDeal) {
				result.code = -1;
				result.msg = "平台扣除票信流转服务费失败";
				
				return result;
			}
			// 增加平台收支记录
			Map<String, Object> dealRemarkParam = new HashMap<String, Object>();
			dealRemarkParam.put("certificate_code", serviceOrderNo);
			dealRemarkParam.put("amount", leader_custodian_fee + "");
			addDeal = dealPlatformService.addPlatformDeal(lender_id,
					leader_custodian_fee,
					t_deal_platform.DealRemark.CUSTODIAN_FETCH_INCOME,
					dealRemarkParam, 0, 0,
					settingService.findSettingValueByKey(SettingKey.COMPANY_NAME));
			if (!addDeal) {
				result.code = -1;
				result.msg = "添加平台票信流转服务费失败";
				
				return result;
			}
		}
		result.code = 1;
		return result;
	}
	
	/***
	 * 转开账款凭证申请
	 * @param signId
	 * @param cpiType
	 * @param paper_money
	 * @param cpiSign
	 * @param type
	 * @param creditorSign
	 * @param currUser
	 * @return
	 */
	public ResultInfo DigitalticketAway(String signId, int cpiType,
			double paper_money, String cpiSign, int type, String creditorSign,CurrUser currUser ){
		ResultInfo result = new ResultInfo();
		 result = Security.decodeSign(creditorSign,
				Constants.BID_ID_SIGN, Constants.VALID_TIME,
				ConfConst.ENCRYPTION_KEY_DES);
		if (result.code < 1) {
			result.code = -1;
			result.msg = "参数非法";
			return result;
		}
		long creditorId = Long.parseLong(result.obj.toString());
		result = Security.decodeSign(cpiSign, Constants.BID_ID_SIGN,
				Constants.VALID_TIME, ConfConst.ENCRYPTION_KEY_DES);
		if (result.code < 1) {
			result.code = -1;
			result.msg = "参数非法";
			return result;
		}
		long cpiId = Long.parseLong(result.obj.toString());
		long user_id = 1l;
		if (currUser != null) {
			user_id = currUser.id;
		}
		// 获取原商票额度信息
		t_commercial_paper_info olcpi = commerciaPaperiInfoService
				.findByID(cpiId);
		if (olcpi == null) {
			result.code = -1;
			result.msg = "请选择质押信息！";
			return result;
		}
		
		// 查询需要开票的账务信息
		t_creditor_right_debt crdList = creditorRightDebtService.findByID(creditorId);
		if (crdList == null) {
			result.code = -1;
			result.msg = "请先选中应付账款信息！";
			return result;
		}
		
		//获取应付账款信息的债权id
		long creditorRightId = crdList.company_id;
		
		//检查商票的授信id
		t_user_credit userCreditCheck = userCreditService.findByID(olcpi.credit_limit_id);
		if(userCreditCheck == null){
			result.code = -1;
			result.msg = "请先申请额度！";
			return result;
		}else{
			if(creditorRightId==userCreditCheck.lender_id){
				result.code = -1;
				result.msg = "不能选中该商票！";
				return result;
			}
		}
		
		//检查商票的原始授信父级id
		List<t_user_credit_detail> orgialUserCreditList = userCreditDetailService.findByCreditLimitId(olcpi.receive_credit_id);
		for(t_user_credit_detail orgialUserCredit : orgialUserCreditList){
			if(userCreditCheck.credit_granting_code.contains(orgialUserCredit.credit_granting_code) && 
					orgialUserCredit.user_id == creditorRightId){
				result.code = -1;
				result.msg = "不能选中该商票！";
				return result;
			}
		}
		
		

		// 商票类型
		int isDigital = olcpi.is_digital;

		// 商票到期日期
		Date paperExpireTime = olcpi.paper_expire_time;

		// 登记时间
		Date time = new Date();

		// 两个日期相隔的天数
		if(time.compareTo(paperExpireTime)!=-1){
			result.code = -1;
			result.msg = "开票的日期不能大于商票的截止日期！";
			return result;
		}
		int dateCount = DateUtil.getDaysDiffCeil(time, paperExpireTime);

		// 获取授信信息
		t_user_credit user_credit = userCreditService
				.findByID(olcpi.receive_credit_id);
		// 额度管理费率
		t_user_credit userCredit = userCreditService
				.findByID(olcpi.credit_limit_id);
		
		if(userCredit == null){
			result.code = -1;
			result.msg = "请设置管理费率！";
			return result;
		}
		
		//票信额度管理费
		double custodian_fee = FeeCalculateUtil.getTransfer(paper_money,time , paperExpireTime, user_credit.custodian_fee);
		
		
		// 票信流转服务费费率
		double fee = Double.valueOf(settingService
				.findSettingValueByKey(SettingKey.CUSTODIAN_FEE));
		
		//票信流转服务费
		double leader_custodian_fee = FeeCalculateUtil.getTransfer(paper_money,time , paperExpireTime, fee);

		/*double custodian_fee = Arith.div(Arith.mul(
				Arith.mul(paper_money, user_credit.custodian_fee), dateCount),
				Arith.mul(30, 100), 2);
*/
		// 获取债权信息
		t_creditor_right_debt crd = creditorRightDebtService
				.findByID(creditorId);
		// 转开控制开关
		t_flow_switch flowSwitch = flowSwitchService.findByID(1);

		// 转开控制开关
		if (flowSwitch.ticket_away == 1 && olcpi.is_digital == 1) {
			result.code = -1;
			result.msg = "转开功能已关闭！";
			return result;
		}
		if (creditorId <= 0) {
			result.code = -1;
			result.msg = "没有债务信息！";
			return result;
		}
		if (paper_money <= 0) {
			result.code = -1;
			result.msg = "请输入转开金额！";
			return result;
		}
		if (paper_money > olcpi.finacing_residue_limit) {
			result.code = -1;
			result.msg = "转开金额不能大于商票剩余可用额度！";
			return result;
		}
		if (paper_money > crd.rest_debt_money) {
			result.code = -1;
			result.msg = "转开金额不能大于债权剩余金额！";
			return result;
		}
		// 数据校验
		result = commerciaPaperiInfoService.savePaperValidate(creditorId,
				paper_money, olcpi.finacing_residue_limit, crd,
				olcpi.is_digital, flowSwitch.ticket_away,
				userCredit.usable_limit, user_id, custodian_fee,
				userCredit.flow_limit, cpiType,userCredit, isDigital,leader_custodian_fee);
		if (result.code < 0) {
			LoggerUtil.error(true, result.msg);
			return result;
		}
		// 凭证号码
		String certificate_code = digitalCommercialPaperService
				.getGrantingCcode(OrderNoUtil.getBillCode(olcpi.bill_code));
		// 新增商票信息
		result = commerciaPaperiInfoService.savePaperInfo(paper_money,
				creditorId, user_credit, cpiId, flowSwitch.ticket_away,
				user_id, certificate_code, crd.contract_name_code, olcpi,
				custodian_fee, cpiType, userCredit, isDigital,leader_custodian_fee);
		if (result.code < 0) {
			LoggerUtil.error(true, result.msg);
			return result;
		}
		//记录用户操作
		Map<String, String> userEventParam = new HashMap<String, String>();
		userEventParam.put("userName", currUser.company_full_name);
		userEventParam.put("ip",Request.current().remoteAddress.toString());
		
		userService.addUserEvent(user_id, t_event_user.Event.TO_TICKETAWAY, userEventParam);
		result.msg="数字凭证转开成功";
		return result;
	}
	
	public JSONObject toDigitalTicket(int showType,JSONArray arrList) {
		String fileName = "数字凭证列表";
		switch (showType) {
		case 1:
			fileName = "待签收数字凭证列表";
			break;

		case 2:
			fileName = "已签收数字凭证列表";
			break;

		case 3:
			fileName = "已拒收数字凭证列表";
			break;
		case 4:
			fileName = "已到期数字凭证列表";
			break;
		case 5:
			fileName = "已逾期数字凭证列表";
			break;
		case 6:
			fileName = "已失效数字凭证列表";
			break;
		case 8:
			fileName = "质押中数字凭证列表";
			break;
		case 9:
			fileName = "已背书数字凭证列表";
			break;
		case 10:
			fileName = "已还款数字凭证列表";
			break;

		default:
			fileName = "数字凭证列表";
			break;
		}
		
		File file = ExcelUtils.export(fileName, arrList, new String[] {
				"账款序号", "数字凭证金额（元）", "担保人", "融通比例", "融通额度不超过（元）", "开票人", "收票人", "开票时间",
				"付款时间", "状态" }, new String[] { "contract_name_code",
				"digital_com_paper_money", "lender_name", "finacing_ratio", "finacing_limit", "drawer",
				"receive_person", "pledge_current_time", "payment_time",
				"digital_com_status" });
		JSONObject obj = new JSONObject();
		obj.put("fileName", fileName);
		obj.put("file", file);
		return obj;
	}
	public ResultInfo cancelTicket(String signId,int type,String company_full_name,long userid) {
				// 签名解密
				ResultInfo result = Security.decodeSign(signId, Constants.BID_ID_SIGN,
						Constants.VALID_TIME, ConfConst.ENCRYPTION_KEY_DES);
				if (result.code < 1) {
					result.code = -1;
					result.msg = "签名失败";
					return result;
				}
				// 获取解密id
				long id = Convert.strToLong(result.obj + "", -1);
				result = digitalCommercialPaperService.cancelDigital(id, type);
				if (result.code < 0) {
					LoggerUtil.error(true, result.msg);
					return result;
				}
				
				Map<String, String> userEventParam = new HashMap<String, String>();
				userEventParam.put("userName", company_full_name);
				userEventParam.put("ip",Request.current().remoteAddress.toString());
				
				if(type == 0){//撤销
					
					userService.addUserEvent(userid, t_event_user.Event.CANCEL_TICKETAWAY, userEventParam);
					
				}
				if(type == 1){//拒收
					userService.addUserEvent(userid, t_event_user.Event.RESUSAL_TICKETAWAY, userEventParam);
					
				}
		return result;
	}
	//转开确认签名
	public ResultInfo confirmTicket(String signId,long userid,String  company_full_name) {
		// 签名解密
				ResultInfo result = Security.decodeSign(signId, Constants.BID_ID_SIGN,
						Constants.VALID_TIME, ConfConst.ENCRYPTION_KEY_DES);
				if (result.code < 1) {
					result.msg = "签名失败";
					return result;
				}
				// 获取解密id
				long id = Convert.strToLong(result.obj + "", -1);
				result = digitalCommercialPaperService.confirmTicket(id, userid);
				if (result.code < 0) {
					LoggerUtil.error(true, result.msg);

				}
				//记录用户操作
				Map<String, String> userEventParam = new HashMap<String, String>();
				userEventParam.put("userName", company_full_name);
				userEventParam.put("ip",Request.current().remoteAddress.toString());
			
				userService.addUserEvent(userid, t_event_user.Event.ACCEPT_TICKETAWAY, userEventParam);
				
		return result;
	}
	//背书申请
	public ResultInfo endorseApply(String signId, String creditorSign,CurrUser currUser) {
				// 签名解密
				ResultInfo result = Security.decodeSign(signId, Constants.BID_ID_SIGN,
						Constants.VALID_TIME, ConfConst.ENCRYPTION_KEY_DES);
				if (result.code < 1) {
					result.msg = "签名失败";
					return result;
				}
				// 获取解密额度表id
				Long id = Convert.strToLong(result.obj + "", -1);

				result = Security.decodeSign(creditorSign, Constants.BID_ID_SIGN,
						Constants.VALID_TIME, ConfConst.ENCRYPTION_KEY_DES);
				if (result.code < 1) {
					result.msg = "签名失败";
					return result;
				}
				// 获取解密额度表id
				Long creditorId = Convert.strToLong(result.obj + "", -1);
				
				//获取数字商票的id
				t_digital_commercial_paper olcpi = digitalCommercialPaperService.findByID(id);
				
				//获取商票的信息
				t_commercial_paper_info cpi = commerciaPaperiInfoService
						.findByID(olcpi.commer_paper_id);
				
				// 查询需要开票的账务信息
				t_creditor_right_debt crdList = creditorRightDebtService.findByID(creditorId);
				if (crdList == null) {
					result.code = -1;
					result.msg = "请先选中应付账款信息！";
					return result;
				}
				
				//获取应付账款信息的债权id
				long creditorRightId = crdList.company_id;
				
				//检查商票的授信id
				t_user_credit userCreditCheck = userCreditService.findByID(cpi.credit_limit_id);
				if(userCreditCheck == null){
					result.code = -1;
					result.msg = "请先申请额度！";
					return result;
				}else{
					if(creditorRightId==userCreditCheck.lender_id){
						result.code = -1;
						result.msg = "不能选中该商票！";
						return result;
					}
				}
				
				//检查商票的原始授信父级id
				List<t_user_credit_detail> orgialUserCreditList = userCreditDetailService.findByCreditLimitId(cpi.receive_credit_id);
				for(t_user_credit_detail orgialUserCredit : orgialUserCreditList){
					if(userCreditCheck.credit_granting_code.contains(orgialUserCredit.credit_granting_code) && 
							orgialUserCredit.user_id == creditorRightId){
						result.code = -1;
						result.msg = "不能选中该商票！";
						return result;
					}
				}
				
				result = digitalCommercialPaperService.endorseApply(id, creditorId);
				if (result.code < 0) {
					result.code = 10;
					LoggerUtil.error(true, result.msg);
					return result;
				}
				
				//记录用户操作
				Map<String, String> userEventParam = new HashMap<String, String>();
				userEventParam.put("userName", currUser.company_full_name);
				userEventParam.put("ip",Request.current().remoteAddress.toString());
				
				userService.addUserEvent(currUser.id, t_event_user.Event.TO_ENDORSE, userEventParam);
				
		return result;
	}
	
	//申请融通
	public ResultInfo limitRequest(String signId,CurrUser currUser) {
				// 签名解密
				ResultInfo result = Security.decodeSign(signId, Constants.BID_ID_SIGN,
						Constants.VALID_TIME, ConfConst.ENCRYPTION_KEY_DES);
				if (result.code < 1) {
					result.msg = "签名失败";
					return result;
				}
				// 获取解密id
				Long id = Convert.strToLong(result.obj + "", -1);
				t_digital_commercial_paper digital_commercial_paper = digitalCommercialPaperService
						.findByID(id);
				if (digital_commercial_paper == null) {
					result.msg = "数字凭证信息查询失败！";
					return result;
				}
				if (digital_commercial_paper.digital_com_status != DigitalStatus.CONFIRM.code) {
					result.msg = "状态非法！";
					return result;
				}
				long user_id = currUser.id;
				if (user_id != digital_commercial_paper.receive_id) {
					result.msg = "不是本人不能操作！";
					return result;
				}
				// 申请额度
				t_commercial_paper_lines commercial_paper_lines = commerciaPaperLinesService
						.findByID(digital_commercial_paper.credit_limit_id);
				t_commercial_paper_lines cpl = new t_commercial_paper_lines(user_id,
						new Date(),
						digital_commercial_paper.certificate_code.substring(2),
						commercial_paper_lines.bond_percent,
						digital_commercial_paper.original_id,
						digital_commercial_paper.debt_creditor_id,
						digital_commercial_paper.digital_com_paper_money,
						digital_commercial_paper.digital_com_paper_money, 1, 1,
						digital_commercial_paper.id, PaperType.DIGITAL_TICKET.code,
						digital_commercial_paper.payment_time);

				if (commercial_paper_lines.oiginal_id == 0) {
					cpl.oiginal_id = commercial_paper_lines.commer_paper_id;
				} else {
					cpl.oiginal_id = commercial_paper_lines.oiginal_id;
				}
				cpl.comer_paper_status = t_commercial_paper_lines.PaperStatus.SIGN_FOR.code;
				boolean save = commerciaPaperLinesService.saveCommercialPaper(cpl);
				if (!save) {
					LoggerUtil.error(true, "融通申请数据异常");
					result.msg = "融通申请数据异常！";
					return result;
				}
				// 修改数字凭证状态
				digital_commercial_paper.digital_com_status = t_digital_commercial_paper.DigitalStatus.PLEDGE.code;

				save = digitalCommercialPaperService.updateStatus(
						DigitalStatus.PLEDGE.code, DigitalStatus.CONFIRM.code,
						digital_commercial_paper.id);
				if (!save) {
					LoggerUtil.error(true, "更新数字凭证状态异常");
					result.msg = "更新数字凭证状态异常！";
					return result;
				}
				// 更新数字账款状态
				t_commercial_paper_info cpi = commerciaPaperiInfoService
						.findByID(digital_commercial_paper.original_id);
				cpi.paper_status = t_commercial_paper_info.TicketStatus.PLEDGE.code;
				cpi = commerciaPaperiInfoService.addTicket(cpi);
				if (cpi == null) {
					LoggerUtil.error(true, "更新数字账款状态异常");
					result.msg = "更新数字账款状态异常！";
					return result;
				}
				
				result.code = 1;
				result.msg = "申请质押成功！";
				
		return result;
	}
	//预览正面
	public ResultInfo previewDigitalTicket(long cpiId, long creditorId) {
		ResultInfo result = new ResultInfo();
		result.code = -1;
		t_commercial_paper_info olcpi = commerciaPaperiInfoService
				.findByID(cpiId);
		if (olcpi == null) {
			result.msg = "请选择质押信息！";
			return result;
		}
		
		// 查询需要开票的账务信息
		t_creditor_right_debt crdList = creditorRightDebtService.findByID(creditorId);
		if (crdList == null) {
			result.msg = "请先选中应付账款信息！";
			return result;
		}
		
		//获取应付账款信息的债权id
		long creditorRightId = crdList.company_id;
		
		//检查商票的授信id
		t_user_credit userCreditCheck = userCreditService.findByID(olcpi.credit_limit_id);
		if(userCreditCheck == null){
			result.msg = "请先申请额度！";
			return result;
		}else{
			if(creditorRightId==userCreditCheck.lender_id){
				result.msg = "不能选中该商票！";
				return result;
			}
		}
		
		//检查商票的原始授信父级id
		List<t_user_credit_detail> orgialUserCreditList = userCreditDetailService.findByCreditLimitId(olcpi.receive_credit_id);
		for(t_user_credit_detail orgialUserCredit : orgialUserCreditList){
			if(userCreditCheck.credit_granting_code.contains(orgialUserCredit.credit_granting_code) && 
					orgialUserCredit.user_id == creditorRightId){
				result.msg = "不能选中该商票！";
				return result;
			}
		}
		result.code = 1;
		result.obj = olcpi;
		return result;
	}
	//逾期还款
	public ResultInfo overdueRepaymen(String signId, double paper_money, CurrUser currUser) {
		
				// 签名解密
				ResultInfo result = new ResultInfo();
				result = Security.decodeSign(signId, Constants.BID_ID_SIGN,
						Constants.VALID_TIME, ConfConst.ENCRYPTION_KEY_DES);
				if (result.code < 1) {
					result.msg = "签名失败";
					return result;
				}
				// 获取解密id
				Long id = Convert.strToLong(result.obj + "", -1);
				t_digital_commercial_paper dcp = digitalCommercialPaperService
						.findByID(id);
				if (dcp == null) {
					result.code = 100;
					result.msg = "没有找到该数字凭证！";
					return result;
				}
				if (paper_money != dcp.digital_com_paper_money) {
					result.code = -1;
					result.msg = "请输入正确还款金额！需要全额还款！";
					return result;
				}
				//long userId = getCurrUser().id;
				if (DigitalStatus.OVERDUE.code != dcp.digital_com_status
						&& DigitalStatus.EXPIRE.code != dcp.digital_com_status) {
					result.code = -1;
					result.msg = "状态非法！";
					return result;
				}
				String serviceOrderNo = OrderNoUtil.getNormalOrderNo(
						ServiceType.REPAYMENT, "");

				// 还款准备
				result = digitalCommercialPaperService.normalRepayment(currUser.id, dcp);
				if (result.code == -4) {
					return result;
				}
				if (result.code < 0) {
					result.msg = result.msg;
					return result;
				}
				// 状态变更
				result = digitalCommercialPaperService.stateChange(id,
						dcp.digital_com_status);
				if (result.code < 0) {
					LoggerUtil.info(true, result.msg);
					return result;
				}
				result = digitalCommercialPaperService.doRepayment(dcp.id,
						serviceOrderNo);
				if (result.code < 0) {
					LoggerUtil.info(true, result.msg);
					return result;
				}
				result.code = 1;
				result.msg = "还款成功！";
				
				//记录用户操作
				Map<String, String> userEventParam = new HashMap<String, String>();
				userEventParam.put("userName", currUser.company_full_name);
				userEventParam.put("ip",Request.current().remoteAddress.toString());
			
				userService.addUserEvent(currUser.id, t_event_user.Event.REFUND, userEventParam);
				
		return result;
	}

	/**
	 *	融通失效后更新
	 * @param consultId
	 * @param amount
	 * @param status
	 * @return
	 * @author liangqiongfeng
	 *@version 2018-4-21 
	 */
	public int updateDigData(Long consultId, Double amount, int status) {
		return digitalCommercialPaperDao.updateDigData(consultId, amount,status);
	}
	
}
